﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Tanmia.Domain;
using Tanmia.Core;
using Tanmia.Windows.UserScenario;
using System.Reflection;
using Tanmia.Basis;

namespace Tanmia.Windows.SecurityScenario
{
    /// <summary>
    /// Interaction logic for SignIn.xaml
    /// </summary>
    public partial class SignIn : Window
    {
        UserDomain userObj = new UserDomain();

        public SignIn()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            IList<User> userList = new List<User>();

        Rest:

            try
            {
                userList = userObj.Gets();
            }
            catch
            {
                if (MessageBox.Show("لا يمكن الوصول إلى محتويات قاعدة البيانات\n\rهل تريد اعادة توليد قاعدة البيانات?", "خطأ", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes, MessageBoxOptions.ServiceNotification) == MessageBoxResult.Yes)
                    GDatabase();
                goto Rest;
            }

            if (userList.Count == 0)
            {
                WindowManager.ShowDialogEditor<UserEdit>();
                goto Rest;
            }

            cmbUsers.ItemsSource = userList;
            cmbUsers.DisplayMemberPath = "Name";
        }

        private void SignIn_Click(object sender, RoutedEventArgs e)
        {
            if (cmbUsers.SelectedItem == null)
                return;

            if (((User)cmbUsers.SelectedItem).Password == txtPassword.Password)
            {
                User.CurrentUser = (User)cmbUsers.SelectedItem;
                WindowManager.ShowWindow<MainWindow>();
                Close();
            }
            else
            {
                MessageBox.Show("كلمة المرور غير صحيحة");
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void GDatabase()
        {
            string appDbRep = "Tanmia.NHibernate";
            bool generateApplicationDatabase = true;

            DatabaseConfiguration dbConfig = new DatabaseConfiguration("NHibernate.config", Assembly.Load(appDbRep));
            dbConfig.BuildSessionFactory();
            if (generateApplicationDatabase)
                dbConfig.GenerateDatabase();
        }
    }
}
